package practice;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import framework.ICSVReader;

public class CSVAppender implements ICSVReader {

	PrintWriter TestWriter = null;
	BufferedReader TestReader = null;
	ArrayList<String> arraycontent = new ArrayList<String>(); 
	ArrayList<String> arraytemp = new ArrayList<String>();
	
	
	/**
	 * Dliclwkej lsdfulkjlks jdflk sdjf
	 * @param lineNum - This has to be the line number you want to read
	 * @return returns the string in the given line
	 * @author prbuddha
	 * 
	 */
	@Override
	public String getLine(int lineNum) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean appendToLine(int lineNum, String fileName) {
		// Write content to file based on line number.  
		
		
		arraytemp = getArrayContent(fileName);
		arraytemp.add(lineNum, "!--New Line--!");
		
		try {
			TestWriter = new PrintWriter(new FileWriter(fileName));
			
			for (String line : arraytemp) 
				TestWriter.println(line);
			
				
			
//			TestWriter.println("!--New Line--!");
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally{
			if(TestWriter!=null)
				TestWriter.close();
			
		}
//		
		
		
//			if(lineNum==0)
//		    {
//				try {
//					TestWriter = new PrintWriter(new FileWriter(fileName));
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				TestWriter.println("---New Line Added----");
//				return true;
//		    }
//			else
//			{
//				arraytemp = getArrayContent(lineNum-1,fileName);
//				 try {
//					TestWriter = new PrintWriter(new FileWriter(fileName));
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				 
//				 for(int a=0;a<arraytemp.size();a++)
//				 {
//					 TestWriter.println(arraytemp.get(a)); 
//				 }
//				 TestWriter.println("---New Line Added----");
//				 TestWriter.close();
//				 arraytemp.clear();	
//				 return true;
//			}
			
	}
	
	public ArrayList<String> getArrayContent(String filepath)
	{
		int i=0;
		String line = null;
		//Read the file content to array list up to line number.
		try {
			TestReader = new BufferedReader(new FileReader(filepath));
			while((line = TestReader.readLine())!= null)
			{
				arraycontent.add(line);
			}
		}
		
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
		
		finally
		{
		  return arraycontent;
		}
		
		}
	
	
		
	}	

